﻿package tools.utils {

	/**
	 * 处理Number的静态方法
	 * @author ase7en
	 * @date 2010-7-9
	 */
	public class NumberFormatter {
		/**
		 * 格式化货币字串
		 * @param number 货币值
		 * @param maxDecimals 最大小数位
		 * @param forceDecimals 是否有小数
		 * @param siStyle 是否国际单位模式
		 * @example 格式化一亿，
		 * <LISTING>
		 * var moneyNum:Number = 100000000;
		 * trace(NumberFormatter.moneyFormat(moneyNum,2,true,false)); //output:100,000,000.00
		 * </LISTING>
		*/
		public static function moneyFormat(number : *, maxDecimals : int = 2, forceDecimals : Boolean = false, siStyle : Boolean = true) : String { 
    
			var i : int = 0, inc : Number = Math.pow(10, maxDecimals), str : String = String(Math.round(inc * Number(number)) / inc); 
    
			var hasSep : Boolean = str.indexOf(".") == -1, sep : int = hasSep ? str.length : str.indexOf("."); 
    
			var ret : String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep + 1); 
    
			if (forceDecimals) for (var j : int = 0;j <= maxDecimals - (str.length - (hasSep ? sep - 1 : sep));j++) ret += "0"; 
    
			while (i + 3 < (str.substr(0, 1) == "-" ? sep - 1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret; 
    
			return str.substr(0, sep - i) + ret; 
		}

/**
		 * 格式化数字位数
		 * @param number 源数据
		 * @param scale 需要保留的位数
		 * <LISTING>
		 * trace(NumberFormatter.numberScale(100.357, 2)); //output 100.46;
		 * trace(NumberFormatter.numberScale(7.23, 4)); //output 7.2300;
		 * </LISTING>
		*/
		public static function numberScale(number:Number, scale:int):String
		{
			
			return number.toFixed(scale);
		}	
	}
}
